/**
 * 
 * 
 * Defender
 * 2013-3-14
 */
package com.ls.fw.web.core.servlet.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.swing.Timer;

import com.ls.fw.web.core.servlet.bean.SessionInfo;


/**
 * 检测用户是否离线
 * @author Defender
 * 2013-3-14
 */
public class ServerListener implements ServletContextListener {

 
	private Timer timer = null;
	//超过10分钟表示退出
	public static final int MAX_MILLIS = 10*60*1000;
	//10秒检查一次
	public static final int INTERNAL = 10*1000;
	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("contextDestroyed");
		timer.stop(); 
		timer = null;
	}

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextInitialized(final ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("contextInitialized");
	     timer = new Timer(INTERNAL,new ActionListener(){
        	@Override
			public void actionPerformed(ActionEvent e) {
        		 System.out.println("INTERNAL");
        		 ServletContext application = arg0.getServletContext();
        	     @SuppressWarnings("unchecked")
				 Map<String,SessionInfo> online =  (Map<String,SessionInfo>)application.getAttribute("online"); 
         	     if(online!=null){
         	    	for(String sessionId : online.keySet()){
            	    	 SessionInfo user = online.get(sessionId);
            	    	 if(user!=null){
            	    		 long time = new Date().getTime()-user.getLastRequestTime().getTime();
            	    		 System.out.println("time:"+time);
            	    		 //超过10分钟表示退出
            	    		 if(time>MAX_MILLIS){ 
            	    			user.getSession().invalidate(); 
            	    		 }
            	    	 }
           	         }  
         	     } 
        	} 
		});
	    timer.start();
	}

}
